import os
import shutil


def split_files_into_subfolders(folder_path, files_per_folder=5):
    # 获取文件夹中的所有文件（排除文件夹）
    all_files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]

    # 计算需要多少个子文件夹
    total_files = len(all_files)
    total_subfolders = (total_files + files_per_folder - 1) // files_per_folder  # 向上取整

    # 遍历文件并将它们移动到子文件夹中
    for i in range(total_subfolders):
        # 创建子文件夹，编号从1开始
        subfolder_name = os.path.join(folder_path, f"subfolder_{i + 1}")
        os.makedirs(subfolder_name, exist_ok=True)

        # 获取当前子文件夹需要的文件
        start_index = i * files_per_folder
        end_index = min(start_index + files_per_folder, total_files)
        current_files = all_files[start_index:end_index]

        # 将文件移动到对应的子文件夹中
        for file_name in current_files:
            src_path = os.path.join(folder_path, file_name)
            dst_path = os.path.join(subfolder_name, file_name)
            shutil.move(src_path, dst_path)

        print(f"子文件夹 {subfolder_name} 已创建，包含 {len(current_files)} 个文件。")


if __name__ == "__main__":
    folder_path = r"D:\客服知识库\data\光纤交换机\2 维护手册 - 副本"  # 替换为你要操作的文件夹路径
    split_files_into_subfolders(folder_path)
